from flask import (
    render_template,
    redirect,
    url_for,
    flash,
    request,
    session,
    jsonify,
)
from extensions import db, LoginForm, RegisterForm, EditProfileForm
from models import UserActual, HouseInfoFinal
from app_helpers import (
    current_user,
    is_ajax_request,
    json_response,
    first_form_error,
)
from . import user_bp


def _load_houses_by_ids(id_list, limit=None):
    cleaned_ids = []
    for value in id_list or []:
        try:
            cleaned_ids.append(int(value))
        except (ValueError, TypeError):
            continue
    if not cleaned_ids:
        return []
    target_ids = cleaned_ids if limit is None else cleaned_ids[:limit]
    houses = HouseInfoFinal.query.filter(HouseInfoFinal.id.in_(target_ids)).all()
    ordered = []
    lookup = {house.id: house for house in houses}
    for hid in target_ids:
        house = lookup.get(hid)
        if house:
            ordered.append(house)
    return ordered


def _render_dashboard(user):
    form = EditProfileForm()
    form.username.data = user.name
    form.email.data = user.email
    form.address.data = user.addr
    collected_houses = _load_houses_by_ids(user.get_collect_ids())
    seen_houses = _load_houses_by_ids(user.get_seen_ids(), limit=12)
    return render_template(
        'user.html',
        user=user,
        form=form,
        registration_time='未知',
        last_login='未知',
        collected_houses=collected_houses,
        seen_houses=seen_houses,
    )


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user():
        if is_ajax_request():
            return json_response(True, session.get('username', ''))
        flash('您已经登录了！', 'info')
        return redirect(url_for('main.index'))

    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            user = UserActual.query.filter_by(name=username).first()
            if user and user.password == password:
                session['user_id'] = user.id
                session['username'] = user.name
                session.permanent = True
                if is_ajax_request():
                    return json_response(True, username)
                flash(f'欢迎回来，{username}！', 'success')
                return redirect(url_for('main.index'))
            if is_ajax_request():
                return json_response(False, '用户名或密码错误！', 400)
            flash('用户名或密码错误！', 'danger')
        elif is_ajax_request():
            return json_response(False, first_form_error(form), 400)
    return render_template('login.html', form=form)


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user():
        if is_ajax_request():
            return json_response(True, session.get('username', ''))
        flash('您已经登录了！', 'info')
        return redirect(url_for('main.index'))

    form = RegisterForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            confirm_password = form.confirm_password.data
            if password != confirm_password:
                message = '两次输入的密码不一致！'
                if is_ajax_request():
                    return json_response(False, message, 400)
                flash(message, 'danger')
                return render_template('register.html', form=form)

            existing_user = UserActual.query.filter_by(name=username).first()
            if existing_user:
                message = '用户名已存在！'
                if is_ajax_request():
                    return json_response(False, message, 400)
                flash(message, 'danger')
                return render_template('register.html', form=form)

            new_user = UserActual(
                name=username,
                password=password,
                email=form.email.data,
                addr='',
                collect_id='',
                seen_id='',
            )
            db.session.add(new_user)
            db.session.commit()
            session['user_id'] = new_user.id
            session['username'] = new_user.name
            session.permanent = True
            if is_ajax_request():
                return json_response(True, username)
            flash('注册成功，已自动为您登录。', 'success')
            return redirect(url_for('user.user_profile'))
        elif is_ajax_request():
            return json_response(False, first_form_error(form), 400)

    return render_template('register.html', form=form)


@user_bp.route('/logout')
def logout():
    session.clear()
    if is_ajax_request():
        return json_response(True, '您已成功退出登录！')
    flash('您已成功退出登录！', 'info')
    return redirect(url_for('main.index'))


@user_bp.route('/user')
def user_profile():
    if not current_user():
        flash('请先登录！', 'warning')
        return redirect(url_for('user.login'))

    user = UserActual.query.get(session['user_id'])
    if not user:
        flash('用户不存在或已被删除，请重新登录。', 'warning')
        return redirect(url_for('user.logout'))
    return _render_dashboard(user)


@user_bp.route('/user/<string:username>')
def user_profile_by_name(username):
    user = current_user()
    if not user or user.name != username:
        flash('请先登录！', 'warning')
        return redirect(url_for('user.login'))
    return _render_dashboard(user)


@user_bp.route('/user/edit', methods=['GET', 'POST'])
def edit_profile():
    if not current_user():
        flash('请先登录！', 'warning')
        return redirect(url_for('user.login'))

    user = UserActual.query.get(session['user_id'])
    if not user:
        flash('用户不存在或已被删除，请重新登录。', 'warning')
        return redirect(url_for('user.logout'))
    form = EditProfileForm()

    if request.method == 'GET':
        form.username.data = user.name
        form.email.data = user.email
        form.address.data = user.addr

    if form.validate_on_submit():
        new_username = form.username.data
        new_email = form.email.data
        new_address = form.address.data

        if new_username != user.name:
            existing_user = UserActual.query.filter_by(name=new_username).first()
            if existing_user and existing_user.id != user.id:
                flash('用户名已存在！', 'danger')
                return render_template('edit_profile.html', form=form, user=user)

        if new_email != user.email:
            existing_email = UserActual.query.filter_by(email=new_email).first()
            if existing_email and existing_email.id != user.id:
                flash('邮箱已被使用！', 'danger')
                return render_template('edit_profile.html', form=form, user=user)

        try:
            user.name = new_username
            user.email = new_email
            user.addr = new_address
            db.session.commit()
            session['username'] = new_username
            flash('用户信息更新成功！', 'success')
            return redirect(url_for('user.user_profile'))
        except Exception as exc:
            db.session.rollback()
            flash(f'操作失败：{exc}', 'danger')
            return render_template('edit_profile.html', form=form, user=user)

    return render_template('edit_profile.html', form=form, user=user)


@user_bp.route('/api/toggle_collect', methods=['POST'])
def toggle_collect():
    user = current_user()
    if not user:
        return jsonify({'success': False, 'error': '请先登录'}), 401

    data = request.get_json(silent=True) or {}
    house_id = data.get('house_id')
    try:
        house_id = int(house_id)
    except (TypeError, ValueError):
        return jsonify({'success': False, 'error': '无效的房源ID'}), 400

    house = HouseInfoFinal.query.get(house_id)
    if not house:
        return jsonify({'success': False, 'error': '房源不存在'}), 404

    try:
        if user.is_collected(house_id):
            user.remove_from_collection(house_id)
            db.session.commit()
            return jsonify({'success': True, 'action': 'uncollect', 'message': '已取消收藏！'})
        user.add_to_collection(house_id)
        db.session.commit()
        return jsonify({'success': True, 'action': 'collect', 'message': '已添加收藏！'})
    except Exception as exc:
        db.session.rollback()
        return jsonify({'success': False, 'error': f'操作失败：{exc}'}), 500


@user_bp.route('/api/clear_seen', methods=['POST'])
def clear_seen():
    user = current_user()
    if not user:
        return jsonify({'success': False, 'error': '请先登录'}), 401

    try:
        user.clear_seen()
        db.session.commit()
        return jsonify({'success': True, 'message': '浏览历史已清空！'})
    except Exception as exc:
        db.session.rollback()
        return jsonify({'success': False, 'error': f'操作失败：{exc}'}), 500
